package redis.inaction.ratelimiter.filter.ratelimit;

import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class TimeWindowLocalRateLimiter {
    private int qps;
    private AtomicInteger val;
    private AtomicBoolean running = new AtomicBoolean(false);
    private final Executor executor = Executors.newSingleThreadExecutor();

    @PostConstruct
    public void init(){
        if( qps <= 0 ){
            throw new IllegalArgumentException("limitValue in rate limiter could not be negative");
        }
        val = new AtomicInteger(qps);
        startRefreshTask();
    }
    public boolean isAllow(){
        int x = val.decrementAndGet();
        return x >= 0;
    }
    private void startRefreshTask(){
        executor.execute(() -> {
            while(running.get()){
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    log.warn("interrupted");
                }
                val.set(qps);
            }
        });
    }
}
